package cc.messcat.entity.system;

import cc.messcat.service.fupin.FamilyService;
import cc.messcat.service.fupin.PoorFamilyService;
import cc.messcat.service.fupin.PoorVillageService;
import cc.messcat.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletContext;
import java.util.Map;

/**
 * 2018/3/1
 * 表数据维护类
 */
@Component
public class TableMaintenance {

    @Autowired
    private PoorFamilyService poorFamilyService;

    @Autowired
    private FamilyService familyService;

    @Autowired
    private PoorVillageService poorVillageService;

    /**
     * 设定或更新贫困村记录的贫困户数
     */
    public String updatePoorFamilyCount(String annual, Long areaID) {
        ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
        //贫困户数
        Long poorFamilyCount = poorFamilyService.getPoorFamilyCount(annual, areaID);
        Object poorFamilyCountMap = servletContext.getAttribute("poorFamilyCount");
        if(poorFamilyCountMap == null) {
            servletContext.setAttribute("poorFamilyCount", Collections.generateHashMap(annual+areaID,poorFamilyCount.toString()));
        } else {
            ((Map)poorFamilyCountMap).put(annual+areaID,poorFamilyCount.toString());
        }

        poorVillageService.updatePoorFamilyCount(annual,areaID,poorFamilyCount);
        return poorFamilyCount.toString();
    }

    /**
     * 设定或更新贫困村记录的贫困人口数
     */
    public String updateFamilyCount(String annual, Long areaID) {
        ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
        //贫困人口数
        Long familyCount = familyService.getFamilyCount(annual, areaID);

        Object familyCountMap = servletContext.getAttribute("familyCount");
        if(familyCountMap == null) {
            servletContext.setAttribute("familyCount", Collections.generateHashMap(annual+areaID,familyCount.toString()));
        } else {
            ((Map)familyCountMap).put(annual+areaID,familyCount.toString());
        }

        poorVillageService.updateFamilyCount(annual,areaID,familyCount);
        return familyCount.toString();
    }

}
